<template>
  <div v-if="visible && room" class="dialog-overlay" @click="handleOverlayClick">
    <div class="dialog" @click.stop>
      <div class="dialog-header">
        <h2>房间信息</h2>
        <div class="header-actions">
          <button class="refresh-btn" @click="refreshRoomStatus" title="刷新房间状态">
            <span>🔄</span>
          </button>
          <button class="close-btn" @click="$emit('close')">
            <span>&times;</span>
          </button>
        </div>
      </div>
      
      <div class="dialog-content">
        <!-- 房间基本信息 -->
        <div class="room-info-section">
          <div class="room-header">
            <div class="room-icon">🎨</div>
            <div class="room-title">
              <h3>{{ room.roomName }}</h3>
            </div>
          </div>
          
          <div class="room-status-badge" :class="getStatusClass(room.status)">
            {{ getStatusText(room.status) }}
          </div>
        </div>
        
        <!-- 房间详细信息 -->
        <div class="room-details">
          <div class="detail-item">
            <span class="detail-label">房间名称:</span>
            <span class="detail-value">{{ room.roomName }}</span>
          </div>
          
          <div class="detail-item">
            <span class="detail-label">当前状态:</span>
            <span class="detail-value" :class="getStatusClass(room.status)">
              {{ getStatusText(room.status) }}
            </span>
          </div>
          
          <div class="detail-item">
            <span class="detail-label">玩家数量:</span>
            <span class="detail-value">
              <span class="player-count">{{ room.playerCount }}</span>
              <span class="separator">/</span>
              <span class="max-players">{{ room.maxPlayers }}</span>
            </span>
          </div>
          
          <div class="detail-item">
            <span class="detail-label">房间类型:</span>
            <span class="detail-value">{{ getRoomType(room.maxPlayers) }}</span>
          </div>
        </div>
        
        <!-- 加入房间表单（不再填写玩家昵称，直接使用当前用户昵称） -->
        <div v-if="room.status === 'waiting' && !isInThisRoom && !isRoomFull" class="join-form">
          <h4>加入房间</h4>
          <button 
            class="join-btn" 
            @click="handleJoinRoom"
            :disabled="isJoining"
          >
            {{ isJoining ? '加入中...' : '加入房间' }}
          </button>
        </div>
        
        <!-- 用户已在房间中，显示进入游戏按钮 -->
        <div v-else-if="room.status === 'waiting' && isInThisRoom" class="join-form">
          <h4>进入游戏</h4>
          <p class="info-text">你已在该房间中，点击下方按钮进入游戏</p>
          <button 
            class="enter-game-btn" 
            @click="handleEnterGame"
          >
            进入游戏
          </button>
        </div>
        
        <div v-else-if="room.status === 'waiting' && isRoomFull" class="room-unavailable">
          <div class="unavailable-icon">🚫</div>
          <p class="unavailable-text">该房间已满员，无法加入</p>
        </div>
        
        <!-- 房间已满或游戏中提示 -->
        <div v-else class="room-unavailable">
          <div class="unavailable-icon">
            {{ room.status === 'playing' ? '🎮' : '🚫' }}
          </div>
          <p class="unavailable-text">
            {{ room.status === 'playing' ? '该房间正在游戏中，无法加入' : '该房间已满员，无法加入' }}
          </p>
        </div>
      </div>
      
      <!-- 错误信息显示 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { useSocketStore } from '@/stores/socket'
import { useGameStore } from '@/stores/game'
import { useRoomStore } from '@/stores/room'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

export default {
  name: 'RoomInfoDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    room: {
      type: Object,
      default: () => ({})
    },
    mock: {
      type: Boolean,
      default: true
    }
  },
  emits: ['close', 'room-joined'],
  setup(props, { emit }) {
    const socketStore = useSocketStore()
    const gameStore = useGameStore()
    
    const userStore = useUserStore()
    const roomStore = useRoomStore()
    const isJoining = ref(false)
    const errorMessage = ref('')
    
    // 监听对话框显示状态，自动获取房间详细信息
    watch(() => props.visible, async (newVisible) => {
      if (newVisible && props.room?.roomId) {
        try {
          // 强制刷新房间信息，确保状态同步
          await roomStore.fetchRoomInfo(props.room.roomId)
          
          // 如果用户不在房间中，清除可能过期的房间状态
          if (roomStore.currentRoom?.roomId === props.room.roomId) {
            const currentUserId = userStore.user?.id
            const currentUserName = userStore.userDisplayName
            
            if (roomStore.currentRoom.members && Array.isArray(roomStore.currentRoom.members)) {
              const isMember = roomStore.currentRoom.members.some(member => 
                (member.id || member.userId) === currentUserId || 
                member.name === currentUserName
              )
              
              if (!isMember) {
                console.log('用户不在房间中，清除过期的房间状态')
                roomStore.currentRoom = null
              }
            }
          }
        } catch (error) {
          console.warn('获取房间详细信息失败:', error)
        }
      }
    }, { immediate: true })
    
    // 手动刷新房间状态
    const refreshRoomStatus = async () => {
      if (props.room?.roomId) {
        try {
          await roomStore.fetchRoomInfo(props.room.roomId)
          ElMessage.success('房间状态已刷新')
        } catch (error) {
          ElMessage.error('刷新房间状态失败')
        }
      }
    }
    
    // 获取房间状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'waiting':
          return '等待中'
        case 'playing':
          return '游戏中'
        case 'finished':
          return '已结束'
        default:
          return '未知'
      }
    }
    
    // 获取房间状态样式类
    const getStatusClass = (status) => {
      switch (status) {
        case 'waiting':
          return 'status-waiting'
        case 'playing':
          return 'status-playing'
        case 'finished':
          return 'status-finished'
        default:
          return ''
      }
    }
    
    // 获取房间类型
    const getRoomType = (maxPlayers) => {
      if (maxPlayers <= 2) return '双人对战'
      if (maxPlayers <= 4) return '小团队'
      if (maxPlayers <= 6) return '中型团队'
      return '大型团队'
    }
    
    // 是否已经在当前展示的房间
    const isInThisRoom = computed(() => {
      // 检查房间ID是否匹配
      if (!roomStore.currentRoom?.roomId || !props.room?.roomId || roomStore.currentRoom.roomId !== props.room.roomId) {
        console.log('房间ID不匹配:', {
          currentRoomId: roomStore.currentRoom?.roomId,
          propsRoomId: props.room?.roomId
        })
        return false
      }
      
      // 获取当前用户信息
      const currentUserId = userStore.user?.id
      const currentUserName = userStore.userDisplayName
      
      console.log('检查用户是否在房间中:', {
        currentUserId,
        currentUserName,
        roomMembers: roomStore.currentRoom.members,
        roomId: props.room.roomId
      })
      
      // 检查房间成员列表
      if (roomStore.currentRoom.members && Array.isArray(roomStore.currentRoom.members)) {
        const isMember = roomStore.currentRoom.members.some(member => 
          (member.id || member.userId) === currentUserId || 
          member.name === currentUserName
        )
        console.log('通过成员列表检查结果:', isMember)
        return isMember
      }
      
      // 如果没有成员列表，检查用户是否真的在房间中
      // 通过API重新验证，避免状态不同步
      console.log('无成员列表，需要重新验证房间状态')
      return false
    })

    // 是否房间已满
    const isRoomFull = computed(() => {
      return props.room.playerCount >= props.room.maxPlayers
    })

    // 处理进入游戏（用户已在房间中）
    const handleEnterGame = () => {
      const displayName = userStore.userDisplayName || userStore.user?.nickname || userStore.user?.username || '玩家'
      
      // 直接进入游戏，不需要重新加入
      gameStore.currentPlayer = displayName
      // 不要在这里设置游戏时间，应该使用房间的实际时长配置
      
      emit('room-joined', {
        roomId: props.room.roomId,
        roomName: props.room.roomName,
        playerName: displayName,
        roomData: { maxPlayers: props.room.maxPlayers }
      })
    }
    
    // 处理加入房间
    const handleJoinRoom = async () => {
      isJoining.value = true
      errorMessage.value = ''
      
      try {
        const displayName = userStore.userDisplayName || userStore.user?.nickname || userStore.user?.username || '玩家'
        const roomData = {
          roomId: props.room.roomId,
          playerName: displayName
        }
        
        if (props.mock) {
          // 模拟模式：直接返回成功
          setTimeout(() => {
            gameStore.currentPlayer = displayName
            // 不要在这里设置游戏时间，应该使用房间的实际时长配置
            emit('room-joined', {
              roomId: roomData.roomId,
              roomName: props.room.roomName,
              playerName: displayName,
              roomData: { maxPlayers: props.room.maxPlayers }
            })
            isJoining.value = false
          }, 600)
          return
        }
        
        const success = socketStore.joinRoom(roomData)
        
        if (success) {
          // 监听加入房间的响应
          socketStore.once('RoomJoined', (data) => {
            if (data.success) {
              // 更新游戏状态
              gameStore.currentPlayer = displayName
              // 只有在数据中明确提供游戏时间时才设置，避免覆盖正确的时间
              if (data.gameTime && typeof data.gameTime === 'number') {
                gameStore.gameTime = data.gameTime
              }
              
              emit('room-joined', {
                roomId: roomData.roomId,
                roomName: props.room.roomName,
                playerName: displayName,
                roomData: data.roomData
              })
            } else {
              errorMessage.value = data.message || '加入房间失败'
            }
            isJoining.value = false
          })
          
          // 监听错误
          socketStore.once('RoomError', (data) => {
            errorMessage.value = data.message || '加入房间时发生错误'
            isJoining.value = false
          })
        } else {
          errorMessage.value = '连接失败，请稍后重试'
          isJoining.value = false
        }
      } catch (error) {
        errorMessage.value = '加入房间失败：' + error.message
        isJoining.value = false
      }
    }
    
    // 处理遮罩层点击
    const handleOverlayClick = () => {
      emit('close')
    }
    
    return {
      isJoining,
      errorMessage,
      getStatusText,
      getStatusClass,
      getRoomType,
      isInThisRoom,
      isRoomFull,
      handleJoinRoom,
      handleOverlayClick,
      refreshRoomStatus,
      handleEnterGame
    }
  }
}
</script>

<style scoped>
.dialog-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.dialog { background: white; border-radius: 12px; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); width: 90%; max-width: 500px; max-height: 90vh; overflow-y: auto; }
.dialog-header { display: flex; justify-content: space-between; align-items: center; padding: 24px 24px 0 24px; border-bottom: 1px solid #e5e7eb; padding-bottom: 16px; }
.dialog-header h2 { margin: 0; font-size: 1.5rem; font-weight: 600; color: #111827; }
.header-actions { display: flex; align-items: center; gap: 8px; }
.refresh-btn { background: none; border: none; font-size: 1.2rem; cursor: pointer; color: #6b7280; padding: 8px; border-radius: 4px; transition: all 0.2s; }
.refresh-btn:hover { color: #374151; background: #f3f4f6; }
.close-btn { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 4px; border-radius: 4px; transition: color 0.2s; }
.close-btn:hover { color: #374151; }
.dialog-content { padding: 24px; }
.room-info-section { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 24px; padding-bottom: 20px; border-bottom: 1px solid #f3f4f6; }
.room-header { display: flex; align-items: center; gap: 16px; }
.room-icon { font-size: 48px; opacity: 0.8; }
.room-title h3 { margin: 0 0 8px 0; font-size: 1.5rem; font-weight: 700; color: #111827; }
.room-id { font-size: 0.875rem; color: #6b7280; font-family: monospace; background: #f3f4f6; padding: 4px 8px; border-radius: 4px; }
.room-status-badge { font-size: 0.75rem; padding: 6px 12px; border-radius: 20px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
.status-waiting { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); color: #d97706; border: 1px solid #fbbf24; }
.status-playing { background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%); color: #059669; border: 1px solid #10b981; }
.status-finished { background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); color: #dc2626; border: 1px solid #f87171; }
.room-details { margin-bottom: 24px; }
.detail-item { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid #f9fafb; }
.detail-item:last-child { border-bottom: none; }
.detail-label { font-weight: 500; color: #6b7280; font-size: 0.875rem; }
.detail-value { font-weight: 600; color: #374151; font-size: 0.875rem; }
.player-count { color: #059669; font-weight: 700; }
.separator { margin: 0 4px; color: #9ca3af; }
.max-players { color: #6b7280; }
.join-form { background: #f9fafb; border-radius: 8px; padding: 20px; border: 1px solid #e5e7eb; }
.join-form h4 { margin: 0 0 16px 0; font-size: 1rem; font-weight: 600; color: #374151; }
.form-group { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
.form-group label { font-weight: 500; color: #374151; font-size: 0.875rem; }
.form-group input { padding: 12px 16px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 1rem; transition: border-color 0.2s, box-shadow 0.2s; }
.form-group input:focus { outline: none; border-color: #10b981; box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1); }
.join-btn { width: 100%; padding: 12px 24px; border: none; border-radius: 8px; font-size: 1rem; font-weight: 500; cursor: pointer; transition: all 0.2s; background-color: #10b981; color: white; }
.join-btn:hover:not(:disabled) { background-color: #059669; }
.join-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.enter-game-btn { width: 100%; padding: 12px 24px; border: none; border-radius: 8px; font-size: 1rem; font-weight: 500; cursor: pointer; transition: all 0.2s; background-color: #3b82f6; color: white; }
.enter-game-btn:hover { background-color: #2563eb; }
.info-text { margin: 0 0 16px 0; color: #6b7280; font-size: 0.875rem; text-align: center; }
.room-unavailable { text-align: center; padding: 32px 20px; background: #f9fafb; border-radius: 8px; border: 1px solid #e5e7eb; }
.unavailable-icon { font-size: 48px; margin-bottom: 16px; opacity: 0.6; }
.unavailable-text { margin: 0; color: #6b7280; font-size: 1rem; font-weight: 500; }
.error-message { margin: 16px 24px 24px 24px; padding: 12px 16px; background-color: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; color: #dc2626; font-size: 0.875rem; }
.debug-info { background: #f3f4f6; border-radius: 8px; padding: 16px; margin-top: 24px; border: 1px solid #e5e7eb; }
.debug-info h4 { margin: 0 0 12px 0; font-size: 1rem; font-weight: 600; color: #374151; }
.debug-info p { margin: 0 0 8px 0; color: #6b7280; font-size: 0.875rem; }
@media (max-width: 640px) { .dialog { width: 95%; margin: 20px; } .dialog-header, .dialog-content { padding: 16px; } .room-info-section { flex-direction: column; gap: 16px; align-items: flex-start; } .room-header { width: 100%; } .room-status-badge { align-self: flex-start; } }
</style> 